package com.winit.openapi.gfs.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.spi.context.CommandContext;
import com.winit.gfs.spi.GfsMerchandiseMatchDetailService;
import com.winit.gfs.spi.GfsMerchandiseMatchService;
import com.winit.gfs.spi.GfsOrderSynHistoryService;
import com.winit.gfs.spi.command.GfsDownloadEbaySKUCommand;
import com.winit.gfs.spi.command.GfsDownloadSKUCommand;
import com.winit.gfs.spi.command.GfsMerchandiseMatchCommand;
import com.winit.gfs.spi.command.GfsMerchandiseMatchDetailCommand;
import com.winit.gfs.spi.command.GfsMerchandiseMatchQueryCommand;
import com.winit.gfs.spi.command.GfsOrderSynHistoryCommand;
import com.winit.gfs.spi.vo.GfsMerchandiseMatchDetailVo;
import com.winit.gfs.spi.vo.GfsMerchandiseMatchVo;
import com.winit.gfs.spi.vo.GfsOrderSynHistoryVO;
import com.winit.gfs.spi.vo.GfsResponseMsg;
import com.winit.gfs.spi.vo.PageVo;
import com.winit.gfs.spi.vo.TeapplixStoreVo;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.DateUtil;
import com.winit.openapi.util.ValidateUtil;

/**
 * 
 * 商品匹配处理Controller
 * 
 * @version
*  <pre>
 * Author	     Version  Date		     Changes
 * changhao.liu  1.0      2018年3月20日         Created
 * </pre>
 * 
 * @since 1.
 */
@Controller
@RequestMapping(value = "/gfs/merchandiseMatch")
public class GfsMerchandiseMatchController extends BaseController {

    private static final Logger              logger = LoggerFactory.getLogger(GfsMerchandiseMatchController.class);

    @Resource
    private GfsMerchandiseMatchService       gfsMerchandiseMatchService;
    @Resource
    private GfsMerchandiseMatchDetailService gfsMerchandiseMatchDetailService;
    @Resource
    private GfsOrderSynHistoryService gfsOrderSynHistoryService;

    
    
    /**
     * 查询商品匹配数据
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 封装参数
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            GfsMerchandiseMatchQueryCommand command = this.buildSearchCommand(json);
            PageVo pageVo = this.buildPageVoParams(json);
            command.setPageVo(pageVo);
            command.setCtx(CommandContext.getContext());
            // 调用接口
            logger.info("查询商品匹配数据，入参：{}", json);
            Page<GfsMerchandiseMatchVo> pageMerchandise = gfsMerchandiseMatchService
                .queryGfsMerchandiseMatchPage(command);
            if (null != pageMerchandise) {
                // 返回结果参数
                Map<String, Object>  data= this.getPageParams(pageMerchandise);
                data.put("list", pageMerchandise.getContent());
                responseMsg.setData(data);
            }
        }

        return SUCCESS;
    }

    private PageVo buildPageVoParams(JSONObject json) {
        int pageNo = ApiConstant.PAGE_NO_DEFAULT;
        int pageSize = ApiConstant.PAGE_SIZE_DEFAULT;
        // pageParams
        if (isExistValue(json, "pageParams")) {
            JSONObject pageParams = json.getJSONObject("pageParams");

            if (ValidateUtil.isIntNumber(pageParams.getString("pageNo"))) {
                pageNo = pageParams.getInteger("pageNo");
                if (pageNo <= 0) {
                    throw new ApiException(ErrorCode.FIELD_ERROR, "pageNo");
                }
            } else if (isExistValue(pageParams, "pageNo") && !ValidateUtil.isIntNumber(pageParams.getString("pageNo"))) {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageNo");
            }

            if (ValidateUtil.isIntNumber(pageParams.getString("pageSize"))) {
                pageSize = pageParams.getInteger("pageSize");
                if (pageSize <= 0) {
                    throw new ApiException(ErrorCode.FIELD_ERROR, "pageSize");
                }
            } else if (isExistValue(pageParams, "pageSize")
                       && !ValidateUtil.isIntNumber(pageParams.getString("pageSize"))) {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageSize");
            }

        }
        PageVo pageVo = new PageVo();
        pageVo.setPageNo(pageNo);
        pageVo.setPageSize(pageSize);

        return pageVo;
    }
    
    /**
     * 解除商品匹配
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/release")
    public String release(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            ValidateUtil.isNotNull(json, "id");
            logger.info("解除商品匹配,入参:{}", json);
            GfsMerchandiseMatchCommand command = new GfsMerchandiseMatchCommand();
            GfsMerchandiseMatchVo vo = new GfsMerchandiseMatchVo();
            vo.setId(json.getLong("id"));
            command.setVo(vo);
            command.setCtx(CommandContext.getContext());
            gfsMerchandiseMatchService.updateGfsMerchandiseMatch(command);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }

    /**
     * 批量解除商品匹配
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/batchRelease")
    public String batchRelease(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            logger.info("批量解除商品匹配,入参：{}", json);
            GfsMerchandiseMatchCommand command = new GfsMerchandiseMatchCommand();

            List<Long> list = new ArrayList<Long>();
            ValidateUtil.validList(json, "idList", true);
            JSONArray idList = json.getJSONArray("idList");
            for (Object object : idList) {
                JSONObject idObj = (JSONObject) object;
                list.add(idObj.getLong("id"));
            }
            command.setIdList(list);
            command.setCtx(CommandContext.getContext());
            gfsMerchandiseMatchService.updateBatchGfsMerchandiseMatch(command);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }

    /**
     * 手工匹配
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/match")
    public String match(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            logger.info("手工匹配，入参：{}", json);
            // 校验参数
            ValidateUtil.isNotNull(json, "vos");
            GfsMerchandiseMatchDetailCommand detailCommand = this.buildMatchCommand(json);
            detailCommand.setCtx(CommandContext.getContext());
            gfsMerchandiseMatchDetailService.createBatchGfsMerchandiseMatchDetail(detailCommand);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }

    /**
     * 构建command参数
     * 
     * @param json
     * @return
     */
    private GfsMerchandiseMatchQueryCommand buildSearchCommand(JSONObject json) {
        GfsMerchandiseMatchQueryCommand command = new GfsMerchandiseMatchQueryCommand();
        GfsMerchandiseMatchVo vo = new GfsMerchandiseMatchVo();
        if (json.containsKey("platform")) {
            vo.setPlatform(json.getString("platform").trim());
        }
        if (json.containsKey("storeAccount")) {
            vo.setStoreAccount(json.getString("storeAccount").trim());
        }
        if (json.containsKey("status")) {
            vo.setStatus(json.getString("status").trim());
        }
        if (json.containsKey("platformItemId")) {
            vo.setPlatformItemId(json.getString("platformItemId").trim());
        }
        if (json.containsKey("platformItemName")) {
            vo.setPlatformItemName(json.getString("platformItemName").trim());
        }
        if (json.containsKey("platformItemSku")) {
            vo.setPlatformItemSku(json.getString("platformItemSku").trim());
        }
        command.setVo(vo);
        return command;
    }

    /**
     * 构建手工匹配command参数
     * 
     * @param json
     * @return
     */
    private GfsMerchandiseMatchDetailCommand buildMatchCommand(JSONObject json) {
        GfsMerchandiseMatchDetailCommand command = new GfsMerchandiseMatchDetailCommand();
        List<GfsMerchandiseMatchDetailVo> voList = new ArrayList<GfsMerchandiseMatchDetailVo>();

        ValidateUtil.validMaxLength(json, "id", 20, true);
        command.setId(json.getLong("id"));
        ValidateUtil.validList(json, "vos", true);
        JSONArray vos = json.getJSONArray("vos");
        for (Object object : vos) {
            GfsMerchandiseMatchDetailVo vo = new GfsMerchandiseMatchDetailVo();
            JSONObject orderNoObj = (JSONObject) object;
            //校验入参字段长度
            ValidateUtil.validMaxLength(orderNoObj, "winitItemSku", 128, true);
            ValidateUtil.validMaxLength(orderNoObj, "winitItemSpecification", 128, false);
            ValidateUtil.validMaxLength(orderNoObj, "winitItemName", 256, true);
            ValidateUtil.validMaxLength(orderNoObj, "winitItemNameEn", 256, true);
            ValidateUtil.validMaxLength(orderNoObj, "winitItemQty", 11, true);
            // winit商品编码
            if (orderNoObj.containsKey("winitItemSku")) {
                vo.setWinitItemSku(orderNoObj.getString("winitItemSku").trim());
            }
            // 规格型号
            if (orderNoObj.containsKey("winitItemSpecification")) {
                vo.setWinitItemSpecification(orderNoObj.getString("winitItemSpecification").trim());
            }
            if (orderNoObj.containsKey("winitItemName")) {
                vo.setWinitItemName(orderNoObj.getString("winitItemName").trim());
            }
            if (orderNoObj.containsKey("winitItemNameEn")) {
                vo.setWinitItemNameEn(orderNoObj.getString("winitItemNameEn").trim());
            }
            if (orderNoObj.containsKey("winitItemQty")) {
                vo.setWinitItemQty(orderNoObj.getInteger("winitItemQty"));
            }
            voList.add(vo);
        }

        command.setVos(voList);
        return command;
    }
    
    
    /**
     * 构建同步平台数据command参数
     * 
     * @param json
     * @return
     */
    private GfsDownloadSKUCommand buildDownloadSkuCommand(JSONObject json) {
        GfsDownloadSKUCommand command = new GfsDownloadSKUCommand();
        List<TeapplixStoreVo> storeList = new ArrayList<TeapplixStoreVo>();

        ValidateUtil.validNotNull(json, "storeType");
        ValidateUtil.validNotNull(json, "syncMode");
        ValidateUtil.validNotNull(json, "storeList");
        ValidateUtil.validNotNull(json, "vsAccountID");
        
        if(!StringUtils.isEmpty(json.getString("webhookEndpointName"))){
            command.setWebhookEndpointName(json.getString("webhookEndpointName").trim());
        }
        command.setStoreType(json.getString("storeType").trim());
        command.setSyncMode(json.getString("syncMode").trim());
        command.setVsAccountID(json.getString("vsAccountID").trim());
        JSONArray list = json.getJSONArray("storeList");
        for (Object object : list) {
            TeapplixStoreVo vo = new TeapplixStoreVo();
            JSONObject storeKeyObj = (JSONObject) object;
            vo.setStoreKey(storeKeyObj.getString("storeKey").trim());
            
            //ebay或amazon平台sellerID必填，其他平台非必填
            if(StringUtils.equalsIgnoreCase("ebay", json.getString("storeType")) ||
                    StringUtils.equalsIgnoreCase("amazon", json.getString("storeType"))){
                ValidateUtil.validNotNull(storeKeyObj, "sellerID");
                vo.setSellerID(storeKeyObj.getString("sellerID").trim());
            }
            
            storeList.add(vo);
        }

        command.setStoreList(storeList);
        return command;
    }

    /**
     * 同步平台商品
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/downloadSku")
    public String downloadSku(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        GfsResponseMsg result = new GfsResponseMsg();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            logger.info("同步平台商品，入参：{}", json);
            // TODO 同步过来的Teapplix sku是否需要校验长度
            GfsDownloadSKUCommand downloadCommand = this.buildDownloadSkuCommand(json);
            downloadCommand.setCtx(CommandContext.getContext());
            result = gfsMerchandiseMatchService.downloadSKU(downloadCommand);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("successCount", result.getSuccessNum());
        data.put("updatedCount", result.getUpdatedNum());
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    /**
     * 同步ebay平台商品
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/downloadEbaySku")
    public String downloadEbaySku(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        GfsResponseMsg result = new GfsResponseMsg();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            logger.info("同步ebay平台商品，入参：{}", json);
            GfsDownloadEbaySKUCommand downloadCommand = this.buildDownloadEbaySkuCommand(json);
            downloadCommand.setCtx(CommandContext.getContext());
            result = gfsMerchandiseMatchService.downloadEbaySKU(downloadCommand);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("successCount", result.getSuccessNum());
        data.put("updatedCount", result.getUpdatedNum());
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    /**
     * 构建同步平台数据command参数
     * 
     * @param json
     * @return
     */
    private GfsDownloadEbaySKUCommand buildDownloadEbaySkuCommand(JSONObject json) {
        GfsDownloadEbaySKUCommand command = new GfsDownloadEbaySKUCommand();
        List<String> ebayAccounts = new ArrayList<String>();

        ValidateUtil.validNotNull(json, "ebayAccounts");
        ValidateUtil.validNotNull(json, "from");
        ValidateUtil.validNotNull(json, "to");
        
        String from = json.getString("from") + " 00:00:00";
        String to = json.getString("to") + " 23:59:59";
        command.setFrom(DateUtil.parse2Date(from, DateUtil.FULL_DATE_STRING));
        command.setTo(DateUtil.parse2Date(to, DateUtil.FULL_DATE_STRING));
        
        JSONArray list = json.getJSONArray("ebayAccounts");
        for (Object object : list) {
            JSONObject storeKeyObj = (JSONObject) object;
            String ebayAccount = storeKeyObj.getString("ebayAccount").trim();
            ebayAccounts.add(ebayAccount);
        }

        command.setEbayAccounts(ebayAccounts);
        return command;
    }

    
    /**
     * 查询同步历史记录
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/querySynHistory")
    public String querySynHistory(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 封装参数
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            GfsOrderSynHistoryCommand command = new GfsOrderSynHistoryCommand();
            if (json.containsKey("platform")) {
                command.setPlatform(json.getString("platform").trim());
            }
            if (json.containsKey("synType")) {
                command.setSynType(json.getString("synType").trim());
            }
            command.setCtx(CommandContext.getContext());
            // 调用接口
            logger.info("查询商品匹配数据，入参：{}", json);
            List<GfsOrderSynHistoryVO> historyList = gfsOrderSynHistoryService.queryGfsSynHistoryByPlatfrom(command);
            if (CollectionUtils.isNotEmpty(historyList)) {
                // 返回结果参数
                Map<String, Object>  data= this.buildParams(historyList);
                responseMsg.setData(data);
            }
        }

        return SUCCESS;
    }
    
    /**
     * 构建返回参数
     * @param historyList
     * @return
     */
    private Map<String, Object> buildParams(List<GfsOrderSynHistoryVO> historyList){
        List<Map<String,Object>> synHistoryList = new ArrayList<Map<String,Object>>();
        for(GfsOrderSynHistoryVO vo : historyList){
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("account", vo.getAccount());
            data.put("sysStartDate", vo.getSysStartDate());
            data.put("synDate", vo.getSynDate());
            data.put("synEbayStartDate", vo.getSynEbayStartDate());
            data.put("synEbayEndDate", vo.getSynEbayEndDate());
            data.put("synNum", vo.getSynNum());
            data.put("sysState", vo.getSysState());
            synHistoryList.add(data);
        }
        Map<String, Object> returnData = new HashMap<String, Object>();
        returnData.put("synHistoryList", synHistoryList);
        return returnData;
    }
    
    
    /**
     * ebay 手工匹配
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/ebayMatch")
    public String ebayMatch(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            logger.info("ebay 手工匹配，入参：{}", json);
            // 校验参数
            ValidateUtil.isNotNull(json, "vos");
            GfsMerchandiseMatchDetailCommand detailCommand = this.buildMatchCommand(json);
            detailCommand.setCtx(CommandContext.getContext());
            gfsMerchandiseMatchDetailService.ebayMatch(detailCommand);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
    
    /**
     * ebay商品匹配--确认、批量确认
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/ebayBatchConfirm")
    public String ebayBatchConfirm(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            logger.info("ebay商品匹配--批量确认,入参：{}", json);
            GfsMerchandiseMatchCommand command = new GfsMerchandiseMatchCommand();

            List<Long> list = new ArrayList<Long>();
            ValidateUtil.validList(json, "idList", true);
            JSONArray idList = json.getJSONArray("idList");
            for (Object object : idList) {
                JSONObject idObj = (JSONObject) object;
                list.add(idObj.getLong("id"));
            }
            command.setIdList(list);
            command.setCtx(CommandContext.getContext());
            gfsMerchandiseMatchService.ebayBatchConfirm(command);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
}
